@using System.Threading
@namespace MudBlazor.UnitTests.TestComponents

<MudDataGrid T="Item" VirtualizeServerData="ServerDataFunc" Virtualize="true" Sortable="true">
    <Columns>
        <PropertyColumn Property="x => x.Name" />
        <PropertyColumn Property="x => x.Value" />
        <PropertyColumn Property="x => x.Misc" SortBy="@(item => item.Misc.Length)" />
    </Columns>
</MudDataGrid>

@code {
    public static string __description__ = @"Test in-browser-sorting of DataGrid. Hold <Ctrl> key when clicking header to extend to multi sort. Hold <Alt> key to unsort a sorted column.
Note that the 'Misc' column is being sorted by length and not by the content itself.";

    private IEnumerable<Item> _items = new List<Item>()
    {
        new Item("B", 42, "555"), 
        new Item("A", 73, "7"), 
        new Item("A", 11, "4444"), 
        new Item("C", 33, "33333"),
        new Item("A", 99, "66"), 
        new Item("C", 44, "1111111"),
        new Item("C", 55, "222222")
    };

    public record Item(string Name, int Value, string Misc);

    private async Task<GridData<Item>> ServerDataFunc(GridStateVirtualize<Item> gridState, CancellationToken token)
    {
        await Task.CompletedTask;
        var result = _items.AsEnumerable();

        var sortDefinitions = gridState.SortDefinitions
            .OrderBy(o => o.Index)
            .ToList();

        // Check if there are sort definitions.
        if (sortDefinitions.Count > 0) 
        {
            var firstSort = sortDefinitions.First();
            result = firstSort.Descending 
                ? result.OrderByDescending(firstSort.SortFunc) 
                : result.OrderBy(firstSort.SortFunc);

            foreach (var s in sortDefinitions.Skip(1))
            {
                result = s.Descending 
                    ? ((IOrderedEnumerable<Item>)result).ThenByDescending(s.SortFunc) 
                    : ((IOrderedEnumerable<Item>)result).ThenBy(s.SortFunc);
            }
        }

        result = result
            .Skip(gridState.StartIndex)
            .Take(gridState.Count)
            .ToList();

        return new GridData<Item>
        {
            Items = result,
            TotalItems = _items.Count()
        };
    }
}